package com.carrie.config.handler;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.HashMap;

/**
 * @author XuHaiLong
 * @since 2025/4/15 09:40
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private  final  ObjectMapper objectMapper  = new ObjectMapper();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        try {
            Object principal = authentication.getPrincipal();//获取用户身份信息
            HashMap<String,Object> map = new HashMap<>();
            map.put("code",0);
            map.put("msg","登录成功");
            map.put("data",principal);
//            String result = objectMapper.writeValueAsString(new Result(0,"success",principal));
            response.setContentType("application/json;charset=utf-8");//响应头
            response.getWriter().println(JSON.toJSONString(map));//写入一个响应结果给前端
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().println("{\"code\": 500, \"message\": \"Internal Server Error\"}");
        }
    }
}
